package com.busfm.service;

import com.busfm.BusfmApplication;
import com.busfm.R;
import com.busfm.R.string;
import com.busfm.activity.HomeActivity;
import com.busfm.media.PlayController;
import com.busfm.media.PlayControllerImpl;
import com.busfm.media.PlayControllerListener;
import com.busfm.model.PlayList;
import com.busfm.model.SongEntity;
import com.busfm.util.Constants;
import com.busfm.util.LogUtil;

import android.Manifest.permission;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiManager.WifiLock;
import android.os.IBinder;
import android.os.RemoteException;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.text.StaticLayout;
import android.util.Log;

public class PlayerService extends Service {
    public static final String ACTION_PLAY = "play";
    public static final String ACTION_NEXT = "next";
    public static final String ACTION_PREV = "prev";
    public static final String ACTION_STOP = "stop";
    public static final String ACTION_PAUSE = "pause";

    private WifiManager mWifiManager;
    private WifiLock mWifiLock;
    private PlayController mPlayerEngine;
    private TelephonyManager mTelephonyManager;
    private PhoneStateListener mPhoneStateListener;
    private NotificationManager mNotificationManager = null;
    private PlayControllerListener mRemoteListener;
    private boolean isPauseByPhone = false;

    @Override
    public IBinder onBind(Intent intent) {
        return serviceStub;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mPlayerEngine = BusfmApplication.getInstance().getConcretePlayerEngine();
        if (null == mPlayerEngine) {
            mPlayerEngine = new PlayControllerImpl();
            BusfmApplication.getInstance().setConcretePlayerEngine(mPlayerEngine);
        }
        mPlayerEngine.setListener(playControllerListener);

        mTelephonyManager = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
        mPhoneStateListener = new PhoneStateListener() {

            @Override
            public void onCallStateChanged(int state, String incomingNumber) {
                if (state == TelephonyManager.CALL_STATE_IDLE) {
                    // resume playback
                    Log.e(Constants.TAG, " PhoneStateListener onCallStateChanged : ");
                    if (mPlayerEngine != null && !mPlayerEngine.getPlaylist().isEmpty() && !mPlayerEngine.isPlaying()
                            && isPauseByPhone) {
                        mPlayerEngine.play();
                        isPauseByPhone = false;
                    }
                } else {
                    Log.e(Constants.TAG, " PhoneStateListener onCallStateChanged : " + incomingNumber);
                    if (mPlayerEngine != null && mPlayerEngine.isPlaying()) {
                        mPlayerEngine.pause();
                        isPauseByPhone = true;
                    }
                }
            }

        };
        mTelephonyManager.listen(mPhoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);

        mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        mWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        mWifiLock = mWifiManager.createWifiLock(Constants.TAG);
        mWifiLock.setReferenceCounted(false);
        mRemoteListener = BusfmApplication.getInstance().getPlayerListener();
    }

    @Override
    public void onStart(Intent intent, int startId) {
        if (null == intent) {
            return;
        }

        String action = intent.getAction();
        Log.i(Constants.TAG, "Player Service onStart - " + action);
        // 暂时使用此种方式进行数据传递

        if (action.equals(ACTION_STOP)) {
            LogUtil.i(Constants.TAG, "quit()");
            // Release Resource
            mPlayerEngine.stop();
            mPlayerEngine = null;
            // unregister listern
            mTelephonyManager.listen(mPhoneStateListener, PhoneStateListener.LISTEN_NONE);
            return;
        }

        if (action.equals(ACTION_PLAY)) {
            LogUtil.i(Constants.TAG, "PlayServiceImpl:play()");
            setPlayList();
            mPlayerEngine.setListener(playControllerListener);
            mPlayerEngine.play();
            return;
        }

        if (action.equals(ACTION_NEXT)) {
            setPlayList();
            mPlayerEngine.next();
            return;
        }

        if (action.equals(ACTION_PREV)) {
            mPlayerEngine.prev();
            return;
        }

        if (action.equals(ACTION_PAUSE)) {
            setPlayList();
            mPlayerEngine.pause();
        }

        super.onStart(intent, startId);
    }

    IplayServiceStub.Stub serviceStub = new IplayServiceStub.Stub() {

        @Override
        public void play() throws RemoteException {
            LogUtil.i(Constants.TAG, "PlayServiceImpl:play()");
            setPlayList();
            mPlayerEngine.setListener(playControllerListener);
            mPlayerEngine.play();
        }

        @Override
        public void next() throws RemoteException {
            setPlayList();
            mPlayerEngine.next();
        }

        @Override
        public void stop() throws RemoteException {
            LogUtil.i(Constants.TAG, "PlayServiceImpl:stop()");
            mPlayerEngine.stop();
        }

        @Override
        public void prev() throws RemoteException {
            mPlayerEngine.prev();
        }

        @Override
        public void pause() throws RemoteException {
            setPlayList();
            mPlayerEngine.pause();
        }

        @Override
        public boolean isPlaying() throws RemoteException {
            return mPlayerEngine.isPlaying();
        }

        @Override
        public void quit() throws RemoteException {
            LogUtil.i(Constants.TAG, "quit()");
            // Release Resource
            mPlayerEngine.stop();
            mPlayerEngine = null;
            // unregister listern
            mTelephonyManager.listen(mPhoneStateListener, PhoneStateListener.LISTEN_NONE);
        }
    };

    private void setPlayList() {
        PlayList playList = BusfmApplication.getInstance().getPlayList();
        if (null != playList && !playList.isEmpty() && playList != mPlayerEngine.getPlaylist()) {
            playList.select(0);
            mPlayerEngine.setPlaylist(playList);
        }
    }

    /**
     * notifySongStart
     * 
     * @param sonEntity
     */
    private void notifySongStart(SongEntity songEntity) {
        String notifyMessage = songEntity.getTitle() + " " + songEntity.getArtist() + " is playing ";
        Notification notification = new Notification(R.drawable.bus_notify, notifyMessage, System.currentTimeMillis());
        PendingIntent pendingIntent = PendingIntent.getActivity(
            this,
            0,
            new Intent(this, HomeActivity.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
                    | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED), 0);
        notification.setLatestEventInfo(this, "busfm :", notifyMessage, pendingIntent);
        notification.flags |= Notification.FLAG_ONGOING_EVENT;
        mNotificationManager.notify(Constants.NotifyID, notification);
    }

    private PlayControllerListener playControllerListener = new PlayControllerListener() {

        @Override
        public void onTrackStreamError() {
            if (null != mRemoteListener) {
                mRemoteListener.onTrackStreamError();
            }
        }

        @Override
        public void onTrackStop() {
            mWifiLock.release();
            if (null != mRemoteListener) {
                mRemoteListener.onTrackStop();
            }
        }

        @Override
        public boolean onTrackStart() {
            mWifiLock.acquire();
            if (null != mRemoteListener) {
                if (!mRemoteListener.onTrackStart())
                    return false;
            }

            return true;
        }

        @Override
        public void onTrackProgress(int seconds) {
            if (null != mRemoteListener) {
                mRemoteListener.onTrackProgress(seconds);
            }
        }

        @Override
        public void onTrackPause() {
            if (null != mRemoteListener) {
                mRemoteListener.onTrackPause();
            }
        }

        @Override
        public void onTrackChanged(SongEntity songEntity) {
            LogUtil.i(Constants.TAG, "onTrackChanged:" + songEntity.title);
            notifySongStart(songEntity);
            if (null != mRemoteListener) {
                mRemoteListener.onTrackChanged(songEntity);
            }

            if (mPlayerEngine.getPlaylist().getSelectedIndex() > mPlayerEngine.getPlaylist().size() - 3) {
                onUpdatePlayList();
            }
        }

        @Override
        public void onTrackBuffering(int percent) {
            LogUtil.i(Constants.TAG, "buffing ： " + percent);
            if (null != mRemoteListener) {
                mRemoteListener.onTrackBuffering(percent);
            }
        }

        @Override
        public void onUpdatePlayList() {
            LogUtil.i(Constants.TAG, "onUpdatePlayList");
            if (null != mRemoteListener) {
                mRemoteListener.onUpdatePlayList();
            }
        }
    };

    @Override
    public void onDestroy() {
        super.onDestroy();
        LogUtil.i(Constants.TAG, "OnDestory:PlayerService");
    }

}
